package com.jack.helloworld.util;

import com.orhanobut.logger.Logger;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


@SuppressWarnings("unchecked")
public class MySystemProperties {
	//android.os.SystemProperties
	@SuppressWarnings("rawtypes")
	private static Class sClass;
	private static Method sMethodGet;
	private static Method sMethodSet;
	private static Method sMethodGetInt;

	static {
		try {
			sClass = Class.forName("android.os.SystemProperties");
			sMethodGet = sClass.getDeclaredMethod("get", new Class[] { String.class });
			sMethodSet = sClass.getDeclaredMethod("set", new Class[] { String.class, String.class });
			sMethodGetInt = sClass.getDeclaredMethod("getInt", new Class[] { String.class, int.class });
		} catch (ClassNotFoundException e) {
            Logger.e(e, "MySystemProperties#ERR: " + e.getMessage());
		} catch (SecurityException e) {
            Logger.e(e, "MySystemProperties#ERR: " + e.getMessage());
		} catch (NoSuchMethodException e) {
            Logger.e(e, "MySystemProperties#ERR: " + e.getMessage());
		}
	}

	public static String get(String key) {
		if (sMethodGet == null)
			return null;
		try {
			Object ret = sMethodGet.invoke(null, key);
			return (String) ret;
		} catch (IllegalArgumentException e) {
            Logger.e(e, "MySystemProperties#get#ERR: " + e.getMessage());
		} catch (IllegalAccessException e) {
            Logger.e(e, "MySystemProperties#get#ERR: " + e.getMessage());
		} catch (InvocationTargetException e) {
            Logger.e(e, "MySystemProperties#get#ERR: " + e.getMessage());
		}
		return null;
	}

	public static String set(String key, String value) {
		if (sMethodSet == null)
			return null;
		try {
			Object ret = sMethodSet.invoke(null, key, value);
			return (String) ret;
		} catch (IllegalArgumentException e) {
            Logger.e(e, "MySystemProperties#set#ERR: " + e.getMessage());
		} catch (IllegalAccessException e) {
            Logger.e(e, "MySystemProperties#set#ERR: " + e.getMessage());
		} catch (InvocationTargetException e) {
            Logger.e(e, "MySystemProperties#set#ERR: " + e.getMessage());
		}
		return null;
	}

	public static int getInt(String key, int def){
		if (sMethodGetInt == null)
			return -100;
		try {
			Object ret = sMethodGetInt.invoke(null, key, def);
			return (Integer) ret;
		} catch (IllegalArgumentException e) {
            Logger.e(e, "MySystemProperties#getInt#ERR: " + e.getMessage());
		} catch (IllegalAccessException e) {
            Logger.e(e, "MySystemProperties#getInt#ERR: " + e.getMessage());
		} catch (InvocationTargetException e) {
            Logger.e(e, "MySystemProperties#getInt#ERR: " + e.getMessage());
		}
		return -100;
	}
}
